var Weather = {};

Weather.srcID = 'msntoolbar';
Weather.url = 'http://weather.partners.msn.com/data.aspx?src='+Weather.srcID+'&culture='+locale.weather.culture+'&degreetype='+locale.weather.std_degree+'&wealocations=';
Weather.searchURL = 'http://weather.partners.msn.com/find.aspx?outputview=search&culture='+locale.weather.culture+'&src='+Weather.srcID+'&weasearchstr=';
Weather.forecastURL = 'http://wetter.msn.com/tenday.aspx?src='+Weather.srcID+'&OCID='+ocid+'&wealocations=';
Weather.mainURL = 'http://wetter.msn.com/?ocid='+ocid;
Weather.msnURL = "";
Weather.imagePath = config.weather_image_str;
Weather.locations = new Array();
Weather.locationCodes = new Array();
Weather.attribution = '';
Weather.degreetype = 'C';
Weather.visible = false;
Weather.locationVisible = false;
Weather.imagerelativeURL = '';
Weather.interval = null;
Weather.isRefresh = false;

Weather.weatherXML = '';

Weather.current = {};
Weather.current.location = "";
Weather.current.temperature = 0;
Weather.current.latitude = 0;
Weather.current.skycode = 0;
Weather.current.skytext = '';
Weather.current.observationtime = 0;
Weather.current.timestamp = 0;
Weather.current.feelslike = 0;
Weather.current.humidity = 0;
Weather.current.windspeed = 0;
Weather.current.weatherIcon = {sunMoonImg:"", weatherImg:"",sky:"", sunMoonRotation:""};

Weather.forecast = new Array(5);
for(var i = 0; i < Weather.forecast.length; i++){
	Weather.forecast[i] = {};
	Weather.forecast[i].low = 0;
	Weather.forecast[i].high = 0;
	Weather.forecast[i].skycodeday = 0;
	Weather.forecast[i].skytextday = '';
	Weather.forecast[i].precip = 0;
	Weather.forecast[i].weatherIcon = {sunMoonImg:"sunMoon_19.png", weatherImg:"",sky:"Sky_Clear2", sunMoonRotation:""};
}

Weather.init = function(){

    Weather.scrollbar = new Scrollbar();
    Weather.scrollbar.init(MSNWidget.root);
    
    //At first, hide everything
    MSNWidget.root.findName("current_large").Visibility = "Visible";
    MSNWidget.root.findName("current_small").Visibility = "Collapsed";

    var obj_txt_change = MSNWidget.root.findName("Weather_ChangeLocation");
    obj_txt_change.addEventListener("MouseLeftButtonDown", Weather.click_ChangeLocation);
    obj_txt_change.Text = locale.weather.changeLocation;
    
    var obj_txt_close = MSNWidget.root.findName("Weather_Close");
    obj_txt_close.addEventListener("MouseLeftButtonDown", Weather.click_ChangeLocation);
    obj_txt_close.Text = locale.weather.close;
    
    var obj_txt_reload = MSNWidget.root.findName("Weather_Reload");
    obj_txt_reload.addEventListener("MouseLeftButtonDown", Weather.click_ChangeLocation);
    obj_txt_reload.Text = locale.weather.reload;
    
    var obj_txt_cancel = MSNWidget.root.findName("Weather_CancelChangeLocation");
    obj_txt_cancel.addEventListener("MouseLeftButtonDown", Weather.click_ChangeLocation);
    obj_txt_cancel.Text = locale.weather.cancelSearchLoc;
    obj_txt_cancel["Canvas.Left"] = obj_txt_cancel.getParent().Width - obj_txt_cancel.ActualWidth - 15;
    
    var obj_txt_clear = MSNWidget.root.findName("Weather_ClearChangeLocation");
    obj_txt_clear.addEventListener("MouseLeftButtonDown", Weather.click_ChangeLocation);
    obj_txt_clear.Text = locale.weather.cleaLocHistory;
    obj_txt_clear["Canvas.Left"] = obj_txt_clear.getParent().Width - obj_txt_clear.ActualWidth - obj_txt_cancel.ActualWidth - 15;
    
    var obj_txt_btn = MSNWidget.root.findName("txtLabel1");
    obj_txt_btn.Text = locale.weather.startSearch;
    obj_txt_btn["Canvas.Left"] = (obj_txt_btn.getParent().Width - obj_txt_btn.ActualWidth)/2;
    
    var obj_loading_txt = MSNWidget.root.findName("WeatherLoadingTxt");
    obj_loading_txt.Text = locale.weather.loading;
    obj_loading_txt["Canvas.Left"] = (MSNWidget.root.findName("Content").Width / 2) - (obj_loading_txt.ActualWidth / 2);
    obj_loading_txt["Canvas.Top"] = (MSNWidget.root.findName("Content").Height / 2) - (obj_loading_txt.ActualHeight / 2);
    
    MSNWidget.root.findName("Sky_Clear1").Source = Weather.imagePath +"sky_Clear.png";
    MSNWidget.root.findName("Sky_Cloudy").Source = Weather.imagePath +"sky_Cloudy.png";
    MSNWidget.root.findName("Sky_Clear2").Source = Weather.imagePath +"sky_Clear.png";
    MSNWidget.root.findName("Sky_Stars").Source = Weather.imagePath +"Sky_Stars.png";
    
    MSNWidget.root.findName("Sky_Clear1_small").Source = Weather.imagePath +"sky_Clear.png";
    MSNWidget.root.findName("Sky_Cloudy_small").Source = Weather.imagePath +"sky_Cloudy.png";
    MSNWidget.root.findName("Sky_Clear2_small").Source = Weather.imagePath +"sky_Clear.png";
    MSNWidget.root.findName("Sky_Stars_small").Source = Weather.imagePath +"Sky_Stars.png";
    
    MSNWidget.root.findName("Shadow_Menu2").Source = Weather.imagePath +"shadow_Menu.png";
    MSNWidget.root.findName("Shadow_Menu3").Source = Weather.imagePath +"shadow_Menu.png";
    MSNWidget.root.findName("Shadow_Menu1").Source = Weather.imagePath +"shadow_Menu.png";
    
    
    MSNWidget.root.findName("smallWeather").addEventListener("MouseLeftButtonDown", GUI.Bar.Events.handleMouseUp );
    MSNWidget.root.findName("smallWeather").addEventListener("MouseEnter", GUI.Bar.Events.handleMouseIn );
    MSNWidget.root.findName("smallWeather").addEventListener("MouseLeave", GUI.Bar.Events.handleMouseOut );
    MSNWidget.root.findName("Forecast_Canvas").addEventListener("MouseLeftButtonDown", Weather.openForecast);
    MSNWidget.root.findName("current_large").addEventListener("MouseLeftButtonDown", Weather.openForecast);
    MSNWidget.root.findName("current_small").addEventListener("MouseLeftButtonDown", Weather.showFlyout);
    
    //Read all the locations from the Settings
    var locations = MSNWidget.platformConnector.loadSettings("locations");
    var locationcodes = MSNWidget.platformConnector.loadSettings("locationcodes");
    if(locations != false){
        var locationsArray = locations.split("--");
        var locationCodesArray = locationcodes.split("--");
        for(var x = 0; x < locationsArray.length; x++){
            if(locationsArray[x] != ""){
                this.locations.push(locationsArray[x]);
                if(x >= locationCodesArray.length || locationCodesArray[x] == ""){
                        Weather.locations.pop();
                        break;
                    }
                this.locationCodes.push(locationCodesArray[x]);
            }
        }
    }
    
    this.resize();
    if(Weather.locationCodes.length > 0)
        Weather.send(Weather.locationCodes[0]);
    else {
        Weather.locationCodes.push(config.weather.defaultCode);
        Weather.locations.push(config.weather.defaultName);
        Weather.send(Weather.locationCodes[0]);
    }
    
    //Set the timer for refreshing the weather
    Weather.refresh();
}

Weather.save = function(){
    
    var loc_str = "";
    var loc_code_str = "";
    for(var i = 0; i < Weather.locations.length; i++){
        loc_str += Weather.locations[i] + "--";
        loc_code_str += Weather.locationCodes[i] + "--";
    }
    
    loc_str = loc_str.substring(0, loc_str.length -2);
    loc_code_str = loc_code_str.substring(0, loc_code_str.length -2);
    
    MSNWidget.platformConnector.saveSettings("locationcodes", loc_code_str);
    MSNWidget.platformConnector.saveSettings("locations", loc_str);
}

Weather.openForecast = function(sender, eventArgs){
    
    var url = "";
    if(Weather.locationCodes.length == 0){
        url = Weather.mainURL;
    } else {
        url = Weather.forecastURL + Weather.locationCodes[0];
    }
    
    window.open(url);
}

Weather.showSmallWeather = function(){
    
    if(arguments.length == 1 && !arguments[0])
        MSNWidget.root.findName("smallWeather").Visibility = "Collapsed";
    else 
        MSNWidget.root.findName("smallWeather").Visibility = "Visible";
    
    if(MSNWidget.platformConnector.isDocked())
        MSNWidget.root.findName("smallWeather_Btn").Visibility = "Collapsed";
    else MSNWidget.root.findName("smallWeather_Btn").Visibility = "Visible";

    var img_sunMoon = MSNWidget.root.findName("smallSunMoonImg");
    if(Weather.current.weatherIcon.sunMoonImg != "")
        img_sunMoon.Source = Weather.imagePath + Weather.current.weatherIcon.sunMoonImg;
    else img_sunMoon.Source = "";
    
    var img_Weather = MSNWidget.root.findName("smallWeatherImg");
    if(Weather.current.weatherIcon.weatherImg != "")
        img_Weather.Source = Weather.imagePath + Weather.current.weatherIcon.weatherImg;
    else img_Weather.Source = "";
    
    var temperature = MSNWidget.root.findName("smallTemperature");
    if(Weather.current.temperature != "")
        temperature.Text = Weather.current.temperature +unescape("%B0")+Weather.degreetype;
    else temperature.Text = "";
    
}

Weather.resize = function(){
    var page = document.getElementById("MSNSilverlight");
    MSNWidget.root.findName("LocationSelection").Width = page.offsetWidth;
    MSNWidget.root.findName("LocationSelectionBg").Width = page.offsetWidth - 20;
    MSNWidget.root.findName("WeatherSearchBox").Width = page.offsetWidth - 20;
    
    var obj_chng = MSNWidget.root.findName("Weather_ChangeLocation");
    obj_chng["Canvas.Left"] = obj_chng.getParent().Width - obj_chng.ActualWidth - 15;
    
    var obj_close = MSNWidget.root.findName("Weather_Close");
    if(MSNWidget.platformConnector.isDocked())
        obj_close.Text = "[x]";
    else obj_close.Text = locale.weather.close;
    obj_close["Canvas.Left"] = (MSNWidget.platformConnector.isDocked()) ? 115 : obj_chng["Canvas.Left"] - obj_close.ActualWidth - 6;
    
    var obj_reload = MSNWidget.root.findName("Weather_Reload");
    obj_reload["Canvas.Left"] = obj_close["Canvas.Left"] - obj_reload.ActualWidth - 6;
    obj_reload.Visibility = (MSNWidget.platformConnector.isDocked()) ? 'Collapsed' : 'Visible';
    
    if(MSNWidget.platformConnector.isDocked()){
            GUI.Bar.checkArrows(News.getCategoryIndex());
        }
        
    var obj_locBtn = MSNWidget.root.findName("cnvWeatherLocation");
    obj_locBtn["Canvas.Left"] = (page.offsetWidth - 20) - obj_locBtn.Width;
    MSNWidget.root.findName("cnvScroll1").Width = MSNWidget.root.findName("LocationSelectionBg").Width;
    MSNWidget.root.findName("cnvScroll2")["Canvas.Left"] = MSNWidget.root.findName("LocationSelectionBg").Width - 20;
    
    var root = MSNWidget.root;
    var docked = MSNWidget.platformConnector.isDocked();
    
    var obj_loading_txt = MSNWidget.root.findName("WeatherLoadingTxt");
    obj_loading_txt["Canvas.Left"] = (MSNWidget.root.findName("Content").Width / 2) - (obj_loading_txt.ActualWidth / 2);
    obj_loading_txt["Canvas.Top"] = (MSNWidget.root.findName("Content").Height / 2) - (obj_loading_txt.ActualHeight / 2);
    
    root.findName("Weather")["Canvas.Top"] = (docked) ? -30 : -15;
    root.findName("Current_SunMoonIcon").Width = (docked) ? 150 : 180;
    root.findName("Current_SunMoonIcon").Height = (docked) ? 150 : 180;
    root.findName("Current_WeatherIcon").Width = (docked) ? 150 : 180;
    root.findName("Current_WeatherIcon").Height = (docked) ? 150 : 180;
    
}

//Gets the new weather-data repeatedly
Weather.refresh = function(){
    var force = false;
    if(arguments.length == 1)
        force = arguments[0];

    if(Weather.interval == null){
        Weather.interval = window.setInterval("Weather.refresh()", config.weather.refreshTime * 60 * 1000);
        return;
    } else if(force === true){
        window.clearInterval(Weather.interval);
        Weather.interval = window.setInterval("Weather.refresh()", config.weather.refreshTime * 60 * 1000);
    }
    
    if(Weather.locationCodes.length == 0 || Weather.locationVisible)
        return; 
    Weather.send(Weather.locationCodes[0]);
}

Weather.click_ChangeLocation = function(sender, mouseEventArgs){ 
    var obj = (MSNWidget.platformConnector.isDocked()) ? flyoutSL : MSNWidget.root;
    switch(sender.Name){
    
        case "Weather_ChangeLocation":
            Weather.locationVisible = true;
            obj.findName("Weather_ClearChangeLocation").Opacity = 1;
            obj.findName("LocationSelection").Opacity = 1;
            obj.findName("Weather_ClearChangeLocation").Visibility = "Visible";
            obj.findName("LocationSelection").Visibility = "Visible";
            obj.findName("Weather2Location").Begin();
            Weather.showLocationList();
            break;
            
        case "Weather_CancelChangeLocation":
            Weather.locationVisible = false;
            SearchBar.root.visibility = "Visible";
            MSNWidget.root.findName("WeatherDisplay").Visibility = "Visible";
            obj.findName("Location2Weather").Begin();
            Weather.clearLocationList();
            break;
            
        case "Weather_ClearChangeLocation":
            Weather.locationVisible = false;
            Weather.clearLocationList();
            Weather.clearLocations();
            Weather.save();
            SearchBar.root.visibility = "Visible";
            obj.findName("Location2Weather").Begin();
            break;
            
        case "Weather_Close":
            Weather.show(false);
            break;
            
        case "Weather_Reload":
            Weather.refresh();
            break;
    }
}

Weather.send = function(locationCode){
    
    Weather.loading(true);
    Weather.clearWeather();
    
    var url = Weather.url + locationCode;
    
    MSNWidget.platformConnector.getWeatherData(url);

}

Weather.search = function(searchstring){
    Weather.loading(true);
    var url = Weather.searchURL + encodeURIComponent(searchstring);
    MSNWidget.platformConnector.getWeatherSearch(url);
}

Weather.hideAllDay = function(){
    MSNWidget.root.findName("Sky_Day_Blue").Visibility = "Collapsed";
    MSNWidget.root.findName("Sky_Day_Grey").Visibility = "Collapsed";
    MSNWidget.root.findName("Sky_Day_Dust").Visibility = "Collapsed";
    MSNWidget.root.findName("Sky_Night").Visibility = "Collapsed";
    
    MSNWidget.root.findName("Sky_Day_Blue_small").Visibility = "Collapsed";
    MSNWidget.root.findName("Sky_Day_Grey_small").Visibility = "Collapsed";
    MSNWidget.root.findName("Sky_Day_Dust_small").Visibility = "Collapsed";
    MSNWidget.root.findName("Sky_Night_small").Visibility = "Collapsed";
}

function WeatherCollapse(sender, eventArgs){
    MSNWidget.root.findName("Weather").Visibility = "Collapsed";
}

/**
*   Show or hide the main weather-view
*/
Weather.show = function(show){
    SearchBar.showButtons(!show);
        
    Weather.showSmallWeather();
    if(show){
        if(Weather.visible)return;
        else Weather.visible = true;
                
        MSNWidget.root.findName("Weather").Opacity = 0;
        MSNWidget.root.findName("Weather").Visibility = "Visible";
        
        MSNWidget.root.findName("News2Weather").begin();
        Weather.showWeather();
    } else {
        if(!Weather.visible)return;
        else Weather.visible = false;
        
        MSNWidget.root.findName("NewsItemsContainer").Opacity = 0;
        MSNWidget.root.findName("Subcat_Scroll").Opacity = 0;
        MSNWidget.root.findName("SubCats").Opacity = 0;
        MSNWidget.root.findName("NewsItemsContainer").Visibility = "Visible";
        MSNWidget.root.findName("Subcat_Scroll").Visibility = "Visible";
        MSNWidget.root.findName("SubCats").Visibility = "Visible";
        
        if(MSNWidget.platformConnector.isDocked()){
            GUI.Bar.checkArrows(News.getCategoryIndex());
            MSNWidget.root.findName("subcat_text").Text = News.getCategory();
            MSNWidget.root.findName("innerSubcat")["Canvas.Left"] = (MSNWidget.root.findName("subcat").getParent().Width / 2) - (MSNWidget.root.findName("subcat_text").ActualWidth / 2);
            MSNWidget.root.findName("subcat_text_Hover").Width = MSNWidget.root.findName("subcat_text").ActualWidth;
            MSNWidget.root.findName("subcat_text_Hover").Height = MSNWidget.root.findName("subcat_text").ActualHeight;
            MSNWidget.platformConnector.flyoutShow(false);
        }
            
        if(MSNWidget.root.findName("NewsItems").children.count == 0)
            News.getNews(MSNWidget.newsCat);
        
        if(Weather.locationVisible)
            MSNWidget.root.findName("Location2Weather").Begin();
        SearchBar.root.visibility = "Visible";
        SearchBar.root.Opacity = 1;
        MSNWidget.root.findName("Weather2News").begin();
    }
}

// Calls the docked or undocked version of the weather
Weather.showWeather = function(){
    SearchBar.showButtons(false);
    Weather.hideAllDay();
    
    //Check if a refresh should be called
//    if(Weather.current.timestamp != 0){
//        var date = new Date();
//        var diff = date.getTime() - Weather.current.timestamp;
//        diff = (diff / 1000) / 60;
//        if(diff > config.weather.refreshTime){
//            if(Weather.isRefresh)
//                Weather.isRefresh = false;
//            else {
//                Weather.isRefresh = true;
//                Weather.refresh();
//            }
//        }
//    }
    
    if(MSNWidget.platformConnector.isDocked()){
        MSNWidget.root.findName("current_small").Visibility = "Visible";
        MSNWidget.root.findName("current_large").Visibility = "Collapsed";
        if(Weather.locationVisible){
            SearchBar.root.Visibility = "Visible";
            MSNWidget.root.findName("Location2Weather").begin();
        }
        Weather.showDocked();
        if(arguments.length == 0)
            Weather.showFlyout();
    } else {
        MSNWidget.root.findName("current_small").Visibility = "Collapsed";
        MSNWidget.root.findName("current_large").Visibility = "Visible";
        Weather.showUndocked();
    }
}

Weather.showDocked = function(){
    Weather.resize();
    Weather.showSmallWeather(false);
     MSNWidget.root.findName("subcat_text").Text = locale.weather.name;
     MSNWidget.root.findName("innerSubcat")["Canvas.Left"] = (MSNWidget.root.findName("subcat").getParent().Width / 2) - (MSNWidget.root.findName("subcat_text").ActualWidth / 2);
     MSNWidget.root.findName("subcat_text_Hover").Width = MSNWidget.root.findName("subcat_text").ActualWidth;
     MSNWidget.root.findName("subcat_text_Hover").Height = MSNWidget.root.findName("subcat_text").ActualHeight;
     
    //Hide Maincat-Arrows
    MSNWidget.root.findName("subcat_main_left_btn").Visibility = "Collapsed";
    MSNWidget.root.findName("subcat_main_right_btn").Visibility = "Collapsed";

    //Show current weather
    MSNWidget.root.findName("Current_Temp_small").Text = Weather.current.temperature +unescape("%B0")+Weather.degreetype; 
    MSNWidget.root.findName("Current_FeelsLike_Text_small").Text = locale.weather.feelslike;
    MSNWidget.root.findName("Current_FeelsLike_Temp_small").Text = Weather.current.feelslike +unescape("%B0")+Weather.degreetype;
    MSNWidget.root.findName("Current_Conditions_small").Text = Weather.current.skytext;    

    if(Weather.current.weatherIcon.sunMoonImg != "")
        MSNWidget.root.findName("Current_SunMoonIcon_small").Source = Weather.imagePath + Weather.current.weatherIcon.sunMoonImg;
    else MSNWidget.root.findName("Current_SunMoonIcon_small").Source = "";

    if(Weather.current.weatherIcon.weatherImg != "")
        MSNWidget.root.findName("Current_WeatherIcon_small").Source = Weather.imagePath + Weather.current.weatherIcon.weatherImg;
    else MSNWidget.root.findName("Current_WeatherIcon_small").Source = "";
    MSNWidget.root.findName(Weather.current.weatherIcon.sky+"_small").Visibility = "Visible";

    MSNWidget.root.findName("Provided_By_small").Text = Weather.attribution;
    MSNWidget.root.findName("Current_TimeStamp_small").Text = Weather.current.observationtime;
    MSNWidget.root.findName("Current_TimeStampLocation_small").Text = Weather.current.location;
    
     //Start the animations
    var anim_pop = MSNWidget.root.findName("Image_PopUp_small");
    anim_pop.begin();
    
    var anim_slide = MSNWidget.root.findName("Image_Slide_small");
    anim_slide.begin();
    
    MSNWidget.root.findName("Forecast_SunMoon").begin();
    
 }
 
 Weather.showUndocked = function(){
 
     MSNWidget.root.findName("subcat_text").Text = locale.weather.name;
     
    //Show current weather
    MSNWidget.root.findName("Current_Temp").Text = Weather.current.temperature +unescape("%B0")+Weather.degreetype; 
    MSNWidget.root.findName("Current_FeelsLike_Text").Text = locale.weather.feelslike;
    MSNWidget.root.findName("Current_FeelsLike_Temp").Text = Weather.current.feelslike +unescape("%B0")+Weather.degreetype;
    MSNWidget.root.findName("Current_Conditions").Text = Weather.current.skytext;    

    if(Weather.current.weatherIcon.sunMoonImg != "")
        MSNWidget.root.findName("Current_SunMoonIcon").Source = Weather.imagePath + Weather.current.weatherIcon.sunMoonImg;
    else MSNWidget.root.findName("Current_SunMoonIcon").Source = "";
    
    if(Weather.current.weatherIcon.weatherImg != "")
        MSNWidget.root.findName("Current_WeatherIcon").Source = Weather.imagePath + Weather.current.weatherIcon.weatherImg;
    else MSNWidget.root.findName("Current_WeatherIcon").Source = "";
    MSNWidget.root.findName(Weather.current.weatherIcon.sky).Visibility = "Visible";
    
    MSNWidget.root.findName("Provided_By").Text = Weather.attribution;
    MSNWidget.root.findName("Current_TimeStamp").Text = Weather.current.observationtime;
    if(Weather.current.location)
        MSNWidget.root.findName("Current_TimeStampLocation").Text = Weather.current.location;
    else MSNWidget.root.findName("Current_TimeStampLocation").Text = locale.weather.noLocation;
    
    for(var i = 0; i < Weather.forecast.length; i++){
        if(Weather.forecast[i].weatherIcon.sunMoonImg)
		    MSNWidget.root.findName("Day_"+i+"_SunMoonIcon").Source = Weather.imagePath + Weather.forecast[i].weatherIcon.sunMoonImg;
	    else MSNWidget.root.findName("Day_"+i+"_SunMoonIcon").Source = "";
		
	    if(Weather.forecast[i].weatherIcon && Weather.forecast[i].weatherIcon.sunMoonRotation)
		    MSNWidget.root.findName("Day_"+i+"_SunMoonIcon_Rotation").ScaleX = Weather.forecast[i].weatherIcon.sunMoonRotation;
	    else MSNWidget.root.findName("Day_"+i+"_SunMoonIcon_Rotation").ScaleX= 1;
		
	    if(Weather.forecast[i].weatherIcon.weatherImg.length > 0)
		    MSNWidget.root.findName("Day_"+i+"_WeatherIcon").Source = Weather.imagePath + Weather.forecast[i].weatherIcon.weatherImg;
	    else MSNWidget.root.findName("Day_"+i+"_WeatherIcon").Source="";
		
	    if(Weather.forecast[i].skytextday){
		    MSNWidget.root.findName("Day_"+i+"_Conditions").Text = Weather.forecast[i].skytextday;
		    MSNWidget.root.findName("Day_"+i+"_Conditions").TextWrapping="Wrap";
	    } else {
		    MSNWidget.root.findName("Day_"+i+"_Conditions").Text = locale.weather.notAvailable;
		    MSNWidget.root.findName("Day_"+i+"_Conditions").TextWrapping="Wrap"
	    }
		
	    if(Weather.forecast[i].high)
		    MSNWidget.root.findName("Day_"+i+"_Hi").Text = Weather.forecast[i].high +unescape("%B0")+ Weather.degreetype;
	    else MSNWidget.root.findName("Day_"+i+"_Hi").Text = "";
		
	    if(Weather.forecast[i].low)
		    MSNWidget.root.findName("Day_"+i+"_Lo").Text = Weather.forecast[i].low +unescape("%B0")+ Weather.degreetype;
	    else MSNWidget.root.findName("Day_"+i+"_Lo").Text = "";
		
	    if(Weather.forecast[i].day)
		    MSNWidget.root.findName("Day_"+i+"_Day").Text = Weather.forecast[i].day;
	    else MSNWidget.root.findName("Day_"+i+"_Day").Text = "";
   }
    
    //Start the animations
    var anim_pop = MSNWidget.root.findName("Image_PopUp");
    anim_pop.begin();
    
    var anim_slide = MSNWidget.root.findName("Image_Slide");
    anim_slide.begin();
    
    MSNWidget.root.findName("Forecast_SunMoon").begin();
 }
 
Weather.showFlyout = function(){

    if(!MSNWidget.platformConnector.flyoutShow()){
        MSNWidget.platformConnector.flyoutShow(true);
    } else {
        Flyout.showWeather();
    }
}
 
Weather.clearWeather = function(){
    Weather.current = {temperature: "",
        latitude: 0,
        location: '',
        skycode: 0,
        skytext: "n/a",
        observationtime: "",
        timestamp: 0,
        feelslike: "",
        humidity: 0,
        windspeed: 0,
        weatherIcon: {sunMoonImg:"sunMoon_19.png", weatherImg:"",sky:"Sky_Clear2", sunMoonRotation:""}};
        
    Weather.forecast = new Array(5);
    for(var i = 0; i < Weather.forecast.length; i++){
	    Weather.forecast[i] = {};
	    Weather.forecast[i].day = "";
	    Weather.forecast[i].low = 0;
	    Weather.forecast[i].high = 0;
	    Weather.forecast[i].skycodeday = 0;
	    Weather.forecast[i].skytextday = '';
	    Weather.forecast[i].precip = 0;
	    Weather.forecast[i].weatherIcon = {sunMoonImg:"sunMoon_19.png", weatherImg:"",sky:"Sky_Clear2", sunMoonRotation:""};
    }
    
    if(MSNWidget.platformConnector.isDocked() && !Weather.visible)
        Weather.showSmallWeather(true);
}

Weather.openPage = function(){
    window.open("http://wetter.msn.com/?ocid="+ocid);
}

Weather.loading = function(isLoading){
    var root = (MSNWidget.platformConnector.isDocked() 
                && MSNWidget.platformConnector.flyoutShow()) ? flyoutSL : MSNWidget.root;
    var obj = root.findName("WeatherLoading");
    
    if(isLoading){
        obj.Visibility = "Visible";
        var animation = root.findName("WeatherLoadingIn");
        animation.Begin();
    } else {
        var animation = root.findName("WeatherLoadingOut");
        animation.Begin();
    }
}

function loadedOut(sender, eventArgs){
    sender.findName("WeatherLoading").Visibility = "Collapsed";
}
 
Weather.notAvailable = function(){
    MSNWidget.root.findName("Current_SunMoonIcon").Source = Weather.imagePath + "sunMoon_19.png";
    MSNWidget.root.findName("smallSunMoonImg").Source = Weather.imagePath + "sunMoon_19.png";
}
 
Weather.getLocationData = function(XML){
    var locationNodes = XML.getElementsByTagName('weather');
    var result = new Array();
    
    if(locationNodes.length == 0)
        Weather.noLocationFound();
    
    for(var i = 0; i < locationNodes.length; i++){
        var location = {};
        var node = locationNodes.item(i);
        location.code = node.getAttribute("weatherlocationcode");
        location.name = node.getAttribute("weatherlocationname");
        location.latitude = node.getAttribute("lat");
        
        var currentNode = node.getElementsByTagName('current').item(0);
        location.temperature = currentNode.getAttribute("temperature");
        location.skycode = currentNode.getAttribute("skycode");
        location.skytext = currentNode.getAttribute("skytext");
        
        location.weatherImage = Weather.WeatherImage(location.skycode, null, null, null);        
        
        result.push(location);
    }
    
    Weather.makeLocationResult(result);
}

Weather.makeLocationResult = function(result){
    var root = (MSNWidget.platformConnector.isDocked()) ? flyoutSL : MSNWidget.root;

    //Calculate the right sizes
    var width = root.findName("LocationSelectionBg").width - 24;
    var fontSize = (MSNWidget.platformConnector.isDocked()) ? 10 : 12;

    for(var x = 0; x < result.length; x++){
    
        var location = result[x];
    
        var xaml_str = '<Canvas xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="'+(width)+'" Height="20" Canvas.Left="0" Canvas.Top="'+(x*20+x)+'">';
        xaml_str += '<Rectangle x:Name="SearchLocationSelected_'+x+'" Cursor="Hand" Width="'+(width)+'" Height="20" '+
                    'Fill="#7F3D3D3D" RadiusX="2" RadiusY="2">'
        xaml_str += '<Rectangle.Stroke>';
        xaml_str += '<RadialGradientBrush><RadialGradientBrush.RelativeTransform>';
        xaml_str += '</RadialGradientBrush.RelativeTransform>';
        xaml_str += '<GradientStop Color="#FFFFFFFF" Offset="0"/>';
        xaml_str += '<GradientStop Color="#3FFFFFFF" Offset="1"/>';
        xaml_str += '</RadialGradientBrush></Rectangle.Stroke></Rectangle>';
        xaml_str += '<Rectangle x:Name="SearchLocationSelected_'+x+'_Hover" IsHitTestVisible="False" Width="'+(width)+'" Height="18" ';
        xaml_str += 'Canvas.Left="1" Canvas.Top="1" Opacity="0">';
        xaml_str += '<Rectangle.Fill><LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">';
        xaml_str += '<GradientStop Color="#33E85700" Offset="0"/>';
        xaml_str += '<GradientStop Color="#FFE85700" Offset="0.5"/>';
        xaml_str += '<GradientStop Color="#FFC44900" Offset="0.51"/>';
        xaml_str += '<GradientStop Color="#CCA83F00" Offset="1"/>';
        xaml_str += '</LinearGradientBrush></Rectangle.Fill></Rectangle>';
        xaml_str += '<Rectangle IsHitTestVisible="False" Width="100" Height="18" RadiusX="2" RadiusY="2" Canvas.Left="'+(width-100)+'" Canvas.Top="1">';
        xaml_str += '<Rectangle.Fill><LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">';
        xaml_str += '<GradientStop Color="#FF000000" Offset="0"/>';
        xaml_str += '<GradientStop Color="#00000000" Offset="1"/>';
        xaml_str += '</LinearGradientBrush></Rectangle.Fill></Rectangle>';
        xaml_str += '<TextBlock x:Name="LocCode_'+x+'" Visibility="Collapsed" />';
        xaml_str += '<TextBlock x:Name="LocName_'+x+'" IsHitTestVisible="False" Width="400" Height="18" Canvas.Left="3" Canvas.Top="3" FontFamily="Arial" FontSize="'+fontSize+'" Foreground="#B2FFFFFF" TextWrapping="Wrap" FontStyle="Normal"/>';
        xaml_str += '<Image IsHitTestVisible="False" Width="20" Height="20" Canvas.Left="'+(width - 85)+'" x:Name="LocSunMoon_'+x+'" Canvas.Top="0"/>';
        xaml_str += '<Image IsHitTestVisible="False" Width="20" Height="20" Canvas.Left="'+(width - 85)+'" x:Name="LocCond_'+x+'" Canvas.Top="0"/>';
        xaml_str += '<TextBlock IsHitTestVisible="False" x:Name="LocCurrTemp_'+x+'" Width="40" Height="18" Canvas.Left="'+(width - 35 )+'" Canvas.Top="3" FontFamily="Arial" FontSize="12" Foreground="#FFFFFFFF" TextWrapping="Wrap" FontStyle="Normal"/>';
        xaml_str += '<Rectangle IsHitTestVisible="False" Width="1" Height="18" Canvas.Left="'+(width-101)+'" Canvas.Top="1"><Rectangle.Fill>';
        xaml_str += '<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">';
        xaml_str += '<GradientStop Color="#7F000000" Offset="0"/>';
        xaml_str += '<GradientStop Color="#7F000000" Offset="1"/>';
        xaml_str += '<GradientStop Color="#FF000000" Offset="0.5"/>';
        xaml_str += '</LinearGradientBrush></Rectangle.Fill></Rectangle>';
        xaml_str += '<Rectangle IsHitTestVisible="False" Width="1" Height="18" Canvas.Left="'+(width-100)+'" Canvas.Top="1">';
        xaml_str += '<Rectangle.Fill><LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">';
        xaml_str += '<GradientStop Color="#33FFFFFF" Offset="0"/>';
        xaml_str += '<GradientStop Color="#33FFFFFF" Offset="1"/>';
        xaml_str += '<GradientStop Color="#7FFFFFFF" Offset="0.5"/></LinearGradientBrush></Rectangle.Fill></Rectangle>';
        xaml_str += '<Rectangle IsHitTestVisible="False" Width="1" Height="18" Canvas.Left="'+(width-51)+'" Canvas.Top="1">';
        xaml_str += '<Rectangle.Fill><LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">';
        xaml_str += '<GradientStop Color="#7F000000" Offset="0"/>';
        xaml_str += '<GradientStop Color="#7F000000" Offset="1"/>';
        xaml_str += '<GradientStop Color="#FF000000" Offset="0.5"/>';
        xaml_str += '</LinearGradientBrush></Rectangle.Fill></Rectangle>';
        xaml_str += '<Rectangle IsHitTestVisible="False" Width="1" Height="18" Canvas.Left="'+(width-50)+'" Canvas.Top="1">';
        xaml_str += '<Rectangle.Fill><LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">';
        xaml_str += '<GradientStop Color="#33FFFFFF" Offset="0"/>';
        xaml_str += '<GradientStop Color="#33FFFFFF" Offset="1"/>';
        xaml_str += '<GradientStop Color="#7FFFFFFF" Offset="0.5"/>';
        xaml_str += '</LinearGradientBrush></Rectangle.Fill></Rectangle></Canvas>';
        
        var xaml_obj = root.getHost().content.createFromXaml(xaml_str);
        xaml_obj.findName("LocName_"+x).Text = location.name;
        xaml_obj.findName("LocCode_"+x).Text = location.code;
        xaml_obj.findName("LocCurrTemp_"+x).Text = location.temperature;
        if(location.weatherImage.sunMoonImg != "")
            xaml_obj.findName("LocSunMoon_"+x).Source = Weather.imagePath + location.weatherImage.sunMoonImg;
        else xaml_obj.findName("LocSunMoon_"+x).Source = "";
        xaml_obj.findName("LocCond_"+x).Source = Weather.imagePath + location.weatherImage.weatherImg;
        xaml_obj.findName('SearchLocationSelected_'+x).addEventListener("MouseEnter", Weather.loc_mouseIn);
        xaml_obj.findName('SearchLocationSelected_'+x).addEventListener("MouseLeave", Weather.loc_mouseOut);
        xaml_obj.findName('SearchLocationSelected_'+x).addEventListener("MouseLeftButtonDown", Weather.loc_mouseClick);
        root.findName("WeatherContent").children.add(xaml_obj);
    }
    //Reset the content-area
    root.findName("WeatherContent")["Canvas.Top"] = 0;
    
    //Adjust the scrollbar
    if(MSNWidget.platformConnector.isDocked())
        Flyout.scrollbar.sizeSlider();
    else
        Weather.scrollbar.sizeSlider();
}

Weather.noLocationFound  = function(){

}

//Shows a list of all the previosly selected weatherlocations
Weather.showLocationList = function(){
    var root = (MSNWidget.platformConnector.isDocked()) ? flyoutSL : MSNWidget.root;

    if(Weather.locations.length == 0)return;
   
    var width = root.findName("LocationSelectionBg").Width - 20;
    
    for(var x = 1; x < this.locations.length; x++){
        var xaml_str = '<Canvas xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="'+width+'" ';
        xaml_str += 'Height="20" Canvas.Left="0" Canvas.Top="'+((x-1)*20+x)+'">';
        xaml_str += '<Rectangle x:Name="WeatheLocationSelected_'+x+'" ';
        xaml_str += 'MouseLeave="WeatherLocationSearch_RollOut" Cursor="Hand" Width="'+width+'" Height="20" Fill="#7F3D3D3D" ';
        xaml_str += 'RadiusX="2" RadiusY="2">';
        xaml_str += '<Rectangle.Stroke><RadialGradientBrush>';
        xaml_str += '<RadialGradientBrush.RelativeTransform><TransformGroup>';
        xaml_str += '<ScaleTransform CenterX="0.5" CenterY="0.5" ScaleX="1.052" ScaleY="2.306"/>';
        xaml_str += '<SkewTransform AngleX="0" AngleY="0" CenterX="0.5" CenterY="0.5"/>';
        xaml_str += '<RotateTransform Angle="0" CenterX="0.5" CenterY="0.5"/>';
        xaml_str += '<TranslateTransform X="0" Y="-0.072"/></TransformGroup>';
        xaml_str += '</RadialGradientBrush.RelativeTransform>';
        xaml_str += '<GradientStop Color="#FFFFFFFF" Offset="0"/>';
        xaml_str += '<GradientStop Color="#3FFFFFFF" Offset="1"/></RadialGradientBrush></Rectangle.Stroke></Rectangle>';
        
        xaml_str += '<Rectangle x:Name="WeatheLocationSelected_'+x+'_Hover" IsHitTestVisible="False" Width="'+(width-2)+'" ';
        xaml_str += 'Height="18" Canvas.Left="1" Canvas.Top="1" Opacity="0" RadiusX="2" RadiusY="2"><Rectangle.Fill>';
        xaml_str += '<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">';
        xaml_str += '<GradientStop Color="#33E85700" Offset="0"/>';
        xaml_str += '<GradientStop Color="#FFE85700" Offset="0.5"/>';
        xaml_str += '<GradientStop Color="#FFC44900" Offset="0.51"/>';
        xaml_str += '<GradientStop Color="#CCA83F00" Offset="1"/>';
        xaml_str += '</LinearGradientBrush></Rectangle.Fill></Rectangle>';
        
        xaml_str += '<TextBlock x:Name="LocationName_'+x+'" IsHitTestVisible="False" Width="400" Height="18" ';
        xaml_str += 'Canvas.Left="8" Canvas.Top="3" FontFamily="Arial" FontSize="12" Foreground="#B2FFFFFF" ';
        xaml_str += 'TextWrapping="Wrap" FontStyle="Normal"/></Canvas>'
        
        var xaml_obj = root.getHost().content.createFromXaml(xaml_str);
        xaml_obj.findName("LocationName_"+x).Text = this.locations[x];
        xaml_obj.findName('WeatheLocationSelected_'+x).addEventListener("MouseEnter", Weather.loc_mouseIn);
        xaml_obj.findName('WeatheLocationSelected_'+x).addEventListener("MouseLeave", Weather.loc_mouseOut);
        xaml_obj.findName('WeatheLocationSelected_'+x).addEventListener("MouseLeftButtonDown", Weather.loc_mouseClick);
        root.findName("WeatherContent").children.add(xaml_obj);        
    }
}

Weather.loc_mouseIn = function(sender, mouseEventArgs){
    var animation = sender.findName("BtnHoverIn");
    if(animation == null)return;
    var btn = sender.name + "_Hover";
    animation.Stop();
    animation["Storyboard.TargetName"] = btn;
    animation.Begin();
}

Weather.loc_mouseOut = function(sender, mouseEventArgs){
    var animation = sender.findName("BtnHoverOut");
    if(animation == null)return;
    animation.Stop();
    animation["Storyboard.TargetName"] = sender.name + "_Hover";
    animation.Begin();
}

Weather.loc_mouseClick = function(sender, mouseEventArgs){
    var root = (MSNWidget.platformConnector.isDocked()) ? flyoutSL : MSNWidget.root;
    //find out, which index the clicked location has
    var index = sender.Name.substring(23);
    var prefix = sender.Name.substring(0, 6);
    
    if(index != "" && prefix == "Weathe"){
        
        index = parseInt(index);
        //Rearrange the locations, so that the selected location is first
        var location = new Array(Weather.locations[index]);
        var locationCode = new Array(Weather.locationCodes[index]);
        Weather.locations.splice(index, 1);
        Weather.locationCodes.splice(index, 1);
        
        Weather.locations = location.concat(Weather.locations);
        Weather.locationCodes = locationCode.concat(Weather.locationCodes);
    } else if(index != "" && prefix == "Search"){
        var obj_name = sender.findName("LocName_"+index);
        var obj_code = sender.findName("LocCode_"+index);
        var location = new Array(obj_name.Text);
        var locationCode = new Array(obj_code.Text);
        Weather.locations = location.concat(Weather.locations);
        Weather.locationCodes = locationCode.concat(Weather.locationCodes);
    } else return;
    
        Weather.save();
        MSNWidget.weatherSearchBar.clear();
        Weather.click_ChangeLocation(root.findName("Weather_CancelChangeLocation"), null);
        Weather.send(Weather.locationCodes[0]);
    
}

Weather.clearLocationList = function(){
    var root = (MSNWidget.platformConnector.isDocked()) ? flyoutSL : MSNWidget.root;
    root.findName("WeatherContent").children.clear();
}

Weather.clearLocations = function(){
   Weather.locations.splice(1, Weather.locations.length - 1);
   Weather.locationCodes.splice(1, Weather.locationCodes.length - 1);
}

Weather.showLocationScrollbar = function(){
    
}

Weather.GetWeatherData = function(weatherXML, reqDegType){
	//try{
		var currentWeatherNode = weatherXML.getElementsByTagName('current').item(0),
		    recdDegType = weatherXML.getElementsByTagName('weather').item(0).getAttribute('degreetype'),
		    weatherNode = weatherXML.getElementsByTagName('weather').item(0);
		    

		
		if(currentWeatherNode!=null){
			
			var latitude = weatherNode.getAttribute('lat');
			if(latitude)
				Weather.current.latitude=latitude;
			
			var location = weatherNode.getAttribute('weatherlocationname');
			if(location)
			    Weather.current.location = location;
			    
			var url = weatherNode.getAttribute('url');
			if(url)
			    Weather.msnURL = url;
			
			var temp = currentWeatherNode.getAttribute('temperature');
			if(temp)
				Weather.current.temperature = Weather.ConvertTemp(temp,recdDegType,reqDegType);
			
			var skytext = currentWeatherNode.getAttribute('skytext');
			if(skytext)
				Weather.current.skytext = skytext;
			
			var feelsLike = currentWeatherNode.getAttribute('feelslike');
			if(feelsLike)
			    Weather.current.feelslike = Weather.ConvertTemp(feelsLike,recdDegType,reqDegType);
			
			var time = currentWeatherNode.getAttribute('observationtime');
			var formattedTime = Weather.returnTimeString(time);
			if(formattedTime){
				Weather.current.observationtime = locale.weather.loc_asOf+" "+formattedTime+" "+locale.weather.loc_in;
				var timezone=Number(weatherXML.getElementsByTagName('weather').item(0).getAttribute('timezone'));
				
				if(isNaN(timezone))
				    timezone=0;
				var date=currentWeatherNode.getAttribute('date'),
				    dateParts=date.split("-"),
				    dateTime=dateParts[1]+"-"+dateParts[2]+"-"+dateParts[0]+" "+time,
				    timestamp=Date.parse(dateTime);
				if(!isNaN(timestamp))
					Weather.current.timestamp=timestamp-timezone*3600000;
			}
			
			if(currentWeatherNode.getAttribute('skycode')
			    && currentWeatherNode.getAttribute('observationtime')
			    && (currentWeatherNode.getAttribute('date')
			        && Weather.current.latitude))
				Weather.current.weatherIcon = Weather.WeatherImage(currentWeatherNode.getAttribute('skycode'),
				    currentWeatherNode.getAttribute('observationtime'),
				    currentWeatherNode.getAttribute('date'),Weather.current.latitude);
				
			var attribution = weatherNode.getAttribute('attribution');
			if(attribution)
			    Weather.attribution=attribution;
			    
			Weather.degreeType=reqDegType
		}
		
		var forecastNodeList = weatherXML.getElementsByTagName('forecast');
		if(forecastNodeList != null && forecastNodeList.length > 0){
		
			var datePart = currentWeatherNode.getAttribute('date').split("-"),
				currDate = new Date(Number(datePart[0]),Number(datePart[1])-1,Number(datePart[2])),
				day = currDate.getDay();
			for(var i=0; i<forecastNodeList.length; i++){
				var foreCastNode=forecastNodeList[i];
				
				var high=foreCastNode.getAttribute('high');
				if(high)
					Weather.forecast[i].high = Weather.ConvertTemp(high,recdDegType,reqDegType);
				
				var low=foreCastNode.getAttribute('low');
				if(low)
					Weather.forecast[i].low = Weather.ConvertTemp(low,recdDegType,reqDegType);
					
				var skytextday = foreCastNode.getAttribute('skytextday');
				if(skytextday)
					Weather.forecast[i].skytextday=skytextday;
				
				var skycodeday = foreCastNode.getAttribute('skycodeday');
				if(skycodeday)
					Weather.forecast[i].weatherIcon = Weather.WeatherImage(skycodeday,null,null,null,null);

				Weather.forecast[i].day = (i == 0) ? "Heute" : locale.weather.days[day];
				day=++day%7
			}
		}
		Weather.weatherXML = weatherXML;
}

Weather.WeatherImage = function(skycode,time,date,latitude){
	var lat=Number(latitude),
		nightCode,
		sunMoonRotation=1,
		sunMoonIcon="0",
		weatherIcon="0",
		sky="Sky_Day_Blue";
	
	switch(Number(skycode)){
		case 1:sky="Sky_Day_Grey";weatherIcon="6";break;
		case 2:sky="Sky_Day_Grey";weatherIcon="6";break;
		case 3:sky="Sky_Day_Grey";weatherIcon="6";break;
		case 4:sky="Sky_Day_Grey";weatherIcon="6";break;
		case 5:sky="Sky_Day_Grey";weatherIcon="12";break;
		case 6:sky="Sky_Day_Grey";weatherIcon="29";break;
		case 7:sky="Sky_Day_Grey";weatherIcon="24";break;
		case 8:sky="Sky_Day_Grey";weatherIcon="14";break;
		case 9:sky="Sky_Day_Grey";weatherIcon="5";break;
		case 10:sky="Sky_Day_Grey";weatherIcon="14";break;
		case 11:sky="Sky_Day_Grey";weatherIcon="5";break;
		case 12:sky="Sky_Day_Grey";weatherIcon="5";break;
		case 13:sky="Sky_Day_Grey";weatherIcon="11";break;
		case 14:sky="Sky_Day_Grey";weatherIcon="27";break;
		case 15:sky="Sky_Day_Grey";weatherIcon="17";break;
		case 16:sky="Sky_Day_Grey";weatherIcon="11";break;
		case 17:sky="Sky_Day_Grey";weatherIcon="6";break;
		case 18:sky="Sky_Day_Grey";weatherIcon="25";break;
		case 19:sky="Sky_Day_Dust";sunMoonIcon="17";weatherIcon="15";break;
		case 20:weatherIcon="9";break;
		case 21:weatherIcon="10";break;
		case 22:sky="Sky_Day_Grey";weatherIcon="8";break;
		case 23:weatherIcon="16";break;
		case 24:weatherIcon="16";break;
		case 25:weatherIcon="18";break;
		case 26:sky="Sky_Day_Grey";weatherIcon="4";break;
		case 27:nightCode=true;weatherIcon="19";break;
		case 28:sky="Sky_Day_Grey";nightCode=false;sunMoonIcon="17";weatherIcon="3";break;
		case 29:nightCode=true;weatherIcon="19";break;
		case 30:nightCode=false;sunMoonIcon="17";weatherIcon="3";break;
		case 31:nightCode=true;break;
		case 32:nightCode=false;sunMoonIcon="17";break;
		case 33:nightCode=true;weatherIcon="20";break;
		case 34:nightCode=false;sunMoonIcon="17";weatherIcon="1";break;
		case 35:sky="Sky_Day_Grey";weatherIcon="6";break;
		case 36:nightCode=false;sunMoonIcon="18";break;
		case 37:nightCode=false;sunMoonIcon="17";weatherIcon="7";break;
		case 38:nightCode=false;sunMoonIcon="17";weatherIcon="7";break;
		case 39:nightCode=false;sunMoonIcon="17";weatherIcon="2";break;
		case 40:sky="Sky_Day_Grey";weatherIcon="28";break;
		case 41:nightCode=false;sunMoonIcon="17";weatherIcon="13";break;
		case 42:sky="Sky_Day_Grey";weatherIcon="26";break;
		case 43:sky="Sky_Day_Grey";weatherIcon="26";break;
		case 45:nightCode=true;weatherIcon="21";break;
		case 46:nightCode=true;weatherIcon="23";break;
		case 47:nightCode=true;weatherIcon="22";break;
		default:sky="Sky_Day_Grey";nightCode=false;sunMoonIcon="19";break;
	}
		
	if(time!=null&&nightCode!=false){
		var t=time.split(":"),h=t[0];
		if(h>17)
			nightCode=true
	}
	
	if(nightCode==true)
		sky="Sky_Night";
	
	if(nightCode&&time!=null&&date!=null){
		var lunarcycle=29.5305888531,cD=date.split("-"),
			startDate=new Date(2008,7,1,10,13,0),
			forecastDate=new Date(cD[0],cD[1]-1,cD[2],t[0],t[1],0),
			lunarphase=(Date.parse(forecastDate)-Date.parse(startDate))/1000/60/60/24,
			lunarday=lunarphase/lunarcycle-Math.floor(lunarphase/lunarcycle);
		
		moonage=Math.round(lunarcycle*lunarday);
		switch(moonage){
			case 1:sunMoonIcon="1";break;
			case 2:sunMoonIcon="1";break;
			case 3:sunMoonIcon="2";break;
			case 4:sunMoonIcon="3";break;
			case 5:sunMoonIcon="3";break;
			case 6:sunMoonIcon="4";break;
			case 7:sunMoonIcon="4";break;
			case 8:sunMoonIcon="5";break;
			case 9:sunMoonIcon="6";break;
			case 10:sunMoonIcon="6";break;
			case 11:sunMoonIcon="7";break;
			case 12:sunMoonIcon="7";break;
			case 13:sunMoonIcon="8";break;
			case 14:sunMoonIcon="9";break;
			case 15:sunMoonIcon="9";break;
			case 16:sunMoonIcon="9";break;
			case 17:sunMoonIcon="10";break;
			case 18:sunMoonIcon="11";break;
			case 19:sunMoonIcon="11";break;
			case 20:sunMoonIcon="12";break;
			case 21:sunMoonIcon="12";break;
			case 22:sunMoonIcon="13";break;
			case 23:sunMoonIcon="14";break;
			case 24:sunMoonIcon="14";break;
			case 25:sunMoonIcon="15";break;
			case 26:sunMoonIcon="15";break;
			case 27:sunMoonIcon="16";break;
			case 28:sunMoonIcon="16";break;
			case 29:sunMoonIcon="1";break;
			case 30:sunMoonIcon="1";break;
			default:sunMoonIcon="9";break
		}
		
		if(lat<0)sunMoonRotation=-1
	}else if(nightCode&&time==null&&date==null)
		sunMoonIcon="7";
	
	var w=new Object;
	w.weatherImg="weather_"+weatherIcon+".png";
	w.sunMoonImg="sunMoon_"+sunMoonIcon+".png";
	w.sky=sky;
	w.sunMoonRotation=sunMoonRotation;
	return w
}
	
Weather.ConvertTemp = function(temp,source,dest){
	if(source.toUpperCase()=="C"&&dest.toUpperCase()=="F")
		return Math.round(temp*1.8+32);
	else if(source.toUpperCase()=="F"&&dest.toUpperCase()=="C")
		return Math.round((temp-32)/1.8);
	else return temp
}
	
Weather.returnTimeString = function(time){
    var rT=null;
    if(time&&time.match(/^\d{1,2}:\d{1,2}/)){
        var t=time.split(":"),h=Number(t[0]),m=t[1];
        if(null){
            var ampm;
            if(!h){
                h=12;ampm="am";
            } else if(h==12)
                ampm="pm";
            else if(h>12){
                h-=12;ampm="pm"
            }else ampm="am";
            
            h=h.toString();
            rT=h+":"+m+" "+ampm;
        }else{
            h= h<10 ? "0"+h.toString(): h.toString();
            rT=h+":"+m;
        }
    }return rT;
}

/**************************************************************
*   Weather SearchBar
**************************************************************/

WeatherSearchBar = function(){

    this.obj_cnv = "";
    this.obj_txt = "";
    this.obj_cursor = "";
    this.obj_searchBtn = "";
    this.txt = "";
    this.hasFocus = false;
    this.keyDown = false;
    this.root = null;
}

WeatherSearchBar_init = function() {
    
    WeatherSearchBar.prototype.init = function(root){
        this.root = root;
        this.obj_cnv = root.findName("WeatherSearchBox");
        this.obj_txt = root.findName("WeatherSearchBox");
        this.obj_searchBtn = root.findName("cnvSBNormal1");
        
        var obj_txt_search = root.findName("SearchForYourLocation");
        obj_txt_search.Text = locale.weather.searchForLoc;

        this.obj_searchBtn.addEventListener("MouseLeftButtonDown", delegate(this, this.BtnClick));
        this.obj_cnv.addEventListener("GotFocus", delegate(this, this.TextClick));
        this.obj_cnv.addEventListener("MouseEnter", delegate(this, this.mouseIn));
        this.obj_cnv.addEventListener("MouseLeave", delegate(this, this.mouseOut));
        this.root.findName("SearchForYourLocation").addEventListener("MouseLeftButtonDown", delegate(this, this.TextClick));
        root.addEventListener("KeyDown", delegate(this, this.onKeyDown));
        var obj_btn = root.findName("cnvWeatherLocation");
        obj_btn.addEventListener("MouseEnter", delegate(this, this.btn_enter));
        obj_btn.addEventListener("MouseLeave", delegate(this, this.btn_leave));
        obj_btn.addEventListener("MouseLeftButtonDown", delegate(this, this.btn_down));
    };

    WeatherSearchBar.prototype.btn_down = function(sender, mouseEventArgs){
        var animation = this.root.findName("sb_location_down");
        animation.begin();
        this.BtnClick(sender, mouseEventArgs);
    };

    WeatherSearchBar.prototype.btn_enter = function(sender, mouseEventArgs){
        var animation = this.root.findName("sb_location_in");
        animation.begin();
    };

    WeatherSearchBar.prototype.btn_leave = function(sender, mouseEventArgs){
        var animation = this.root.findName("sb_location_out");
        animation.begin();
    };

    WeatherSearchBar.prototype.TextClick = function(sender, eventArgs){
        
        if(this.hasFocus)return;

        this.obj_txt.Text = "";
        this.root.findName("SearchForYourLocation").Visibility = "Collapsed";
        this.hasFocus = true;
        this.obj_cnv.Focus();
    };

    WeatherSearchBar.prototype.BtnClick = function(sender, eventArgs){
        //this.obj_cursor.Visibility = "Collapsed";
        var animation = this.root.findName("sb_location_up");
        animation.begin();
        Weather.clearLocationList();
        Weather.search(this.obj_txt.Text);
        this.onLooseFocus(sender, eventArgs);
        
        this.obj_txt.Text = "";
    };

    WeatherSearchBar.prototype.onLooseFocus = function(sender, eventArgs){

        if(!this.hasFocus)return;
        if(eventArgs.Source.Name == "SearchBar_Bg" ||
          eventArgs.Source.Name == "SearchBar_Txt" ||
          (eventArgs.Source.getParent() != null && 
            eventArgs.Source.getParent().getParent() != null &&
            eventArgs.Source.getParent().getParent().Name == "SearchBar_More_Container"))return;
        
        this.hasFocus = false;
        
        this.obj_cnv.Text = ""; 
        this.root.findName("SearchForYourLocation").Visibility = "Visible";
        this.hasFocus = false;
        this.root.findName("SearchBar_hidden").Focus();
    };

    WeatherSearchBar.prototype.clear = function(){
        this.obj_txt.Text = "";
        this.txt = "";
        Weather.clearLocationList();
    };

    WeatherSearchBar.prototype.onKeyDown = function(sender, eventArgs){
    
        //If no focus, abort
        if(!this.hasFocus)return;
        
        switch(eventArgs.Key) {
        
          case 3: {
            this.BtnClick(null, eventArgs);
            break;
          }
        }
    };
    
    WeatherSearchBar.prototype.mouseIn = function(sender, eventArgs){
        document.getElementById("MSNSilverlightHost").onclick = function(){};
    };

    WeatherSearchBar.prototype.mouseOut = function(sender, eventArgs){
        document.getElementById("MSNSilverlightHost").onclick = null;
    };
}

/****************************************************************
* Scrollbar
****************************************************************/
Scrollbar = function(){
    this.obj_arrow_top = null;
    this.obj_arrow_bottom = null;
    this.obj_arrow_slider = null;
    this.obj_area = null;
    this.obj_scrollbar = null;
    this.effectiveHeight = 0;
    this.isScrolling = "false";
    this.scrollInterval = null;
    this.mouseY = 0;
    this.LeftMouseBtnPrsd = false;
    this.root = null;
}

Scrollbar_Init = function(){

    Scrollbar.prototype.init = function(root){
        this.root = root;
    
        this.obj_arrow_top = this.root.findName("ScrollArrowUp");
        this.obj_arrow_bottom = this.root.findName("ScrollArrowDown");
        this.obj_arrow_slider = this.root.findName("ScrollGripper");
        this.obj_area = this.root.findName("WeatherContent");
        this.obj_scrollbar = this.root.findName("ScrollBar");
        
        this.obj_arrow_top.addEventListener("MouseLeftButtonDown", delegate(this, this.click));
        this.obj_arrow_bottom.addEventListener("MouseLeftButtonDown", delegate(this, this.click));
        this.obj_scrollbar.addEventListener("MouseLeftButtonDown", delegate(this, this.click));
        
        //Important for avoiding the drag&drop-feature of the gadget
        this.obj_scrollbar.addEventListener("MouseEnter", delegate(this, this.mouseEnter));
        this.obj_scrollbar.addEventListener("MouseEnter", delegate(this, this.mouseLeave));
        
        this.obj_arrow_top.addEventListener("MouseLeftButtonUp", delegate(this, this.releaseClick));
        this.obj_arrow_bottom.addEventListener("MouseLeftButtonUp", delegate(this, this.releaseClick));
        this.obj_scrollbar.addEventListener("MouseLeftButtonUp", delegate(this, this.releaseClick));
        
        this.obj_scrollbar.addEventListener("MouseMove", delegate(this, this.mouseMove));
    };

    Scrollbar.prototype.reset = function(){
       this.obj_area["Canvas.Top"] = 0;
    };

    Scrollbar.prototype.move = function(sender, mouseEventArgs){

    };

    Scrollbar.prototype.scrollDown = function(amount){
        if(this.obj_area == null || this.obj_area.children.count == 0)return;
        
        var areaHeight = this.obj_area.children.count * this.obj_area.children.getItem(0).Height;
        var scroll_left = areaHeight - this.obj_area.Height + this.obj_area["Canvas.Top"];

        if(scroll_left < -10){
            if(this.scrollInterval != null){
                window.clearInterval(this.scrollInterval);
                this.scrollInterval = null;
            }
            return;
        }else {
            if(amount == null){
                this.obj_area["Canvas.Top"]--;
            }
            else {
                if(scroll_left - amount > -10)
                this.obj_area["Canvas.Top"] -= amount;
            }
            
            this.adjustSlider();
        }
    };

    Scrollbar.prototype.scrollUp = function(amount){
        if(this.obj_area == null || this.obj_area.children.count == 0)return;
        
        if(this.obj_area["Canvas.Top"] > 0){
            if(this.scrollInterval != null){
                window.clearInterval(this.scrollInterval);
                this.scrollInterval = null;
            }
            return;
        }else {
             if(amount == null)
                this.obj_area["Canvas.Top"]++;
            else {
                if(amount + this.obj_area["Canvas.Top"] < 0)
                    this.obj_area["Canvas.Top"] += amount;
            }
            
            this.adjustSlider();
        }
    };


    Scrollbar.prototype.sizeSlider = function(){
        var areaHeight = (this.obj_area.children.count * this.obj_area.children.getItem(0).Height) + this.obj_area.children.count;
        var viewport = this.obj_area.Height;
        if(viewport > areaHeight)
            this.obj_scrollbar.Visibility = "Collapsed";
        else {
            this.obj_scrollbar.Visibility = "Visible";
            this.obj_arrow_slider.Height = (viewport / areaHeight) * (viewport - 30);
        }
        
    }

    Scrollbar.prototype.adjustSlider = function(){
        
        var areaHeight = (this.obj_area.children.count * this.obj_area.children.getItem(0).Height) + this.obj_area.children.count;
        var viewport = this.obj_area.Height;
        
        //The Amount of pixels, which the area can be scrolled
        var scrollHeight = areaHeight - viewport;
        
        var ratio = Math.abs(this.obj_area["Canvas.Top"]) / scrollHeight;
        var offset = this.obj_arrow_top.Height + this.obj_arrow_top["Canvas.Top"];
        
        this.obj_arrow_slider["Canvas.Top"] = (this.obj_scrollbar.Height - this.obj_arrow_slider.Height) * ratio;
    };

    Scrollbar.prototype.click = function(sender, mouseEventArgs){
        sender.CaptureMouse();

        switch(sender.Name){
        
            case this.obj_arrow_bottom.Name:
                this.scrollInterval = window.setInterval(delegate(this, this.scrollDown), 10);
                break;
                
            case this.obj_arrow_top.Name:
                this.scrollInterval = window.setInterval(delegate(this, this.scrollUp), 10);
                break;
                
            case this.obj_scrollbar.Name:
                this.mouseY = mouseEventArgs.GetPosition(this.obj_scrollbar).y;
                this.LeftMouseBtnPrsd = true;
                
                break;
        }
    };

    Scrollbar.prototype.releaseClick = function(sender, mouseEventArgs){
        document.getElementById("MSNSilverlightHost").onclick = null;
        if(this.scrollInterval != null){
            window.clearInterval(this.scrollInterval);
            this.scrollInterval = null;
        }
        this.LeftMouseBtnPrsd = false;
        sender.ReleaseMouseCapture();
        
        document.getElementById("MSNSilverlightHost").onclick = null;
    };

    Scrollbar.prototype.mouseMove = function(sender, mouseEventArgs){
        
        var y = mouseEventArgs.getPosition(this.obj_scrollbar).y;

        if(!this.LeftMouseBtnPrsd || this.obj_area.children.count ==  0)return;
        
        if(y < 0 || y > this.obj_scrollbar.Height)return;
        
        //Calculate the scrolling of the area
        var amount_raw = y - this.mouseY;
        
        /*
            How many pixels correspond to 1 pixel on the scrollbar 
        */
        var areaHeight = (this.obj_area.children.count * this.obj_area.children.getItem(0).Height) + this.obj_area.children.count;
        var viewport = this.obj_area.Height;
        
        //The Amount of pixels, which the area can be scrolled
        var scrollHeight = areaHeight - viewport;
        var scrollBarScroll = this.obj_scrollbar.Height - this.obj_arrow_slider.Height;
        var ratio = scrollHeight / scrollBarScroll;
        //debugger;
        if(amount_raw > 0){
            this.scrollDown(amount_raw * ratio);
        } else {
            this.scrollUp(Math.abs(amount_raw * ratio));
        }
        
        this.mouseY = y;
    };

    //If the mouse enters the scrollbar, disable the standard drag&drop-functionality of the sidebar-gadgets
    Scrollbar.prototype.mouseEnter = function(sender, mouseEventArgs){
        document.getElementById("MSNSilverlightHost").onclick = function(e){};
    };

    //If the mouse leave the scrollbar, enable the standard drag&drop-functionality of the sidebar-gadgets
    Scrollbar.prototype.mouseLeave = function(sender, mouseEventArgs){
    };

}